package dinner.web.secure;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AutorisingSystem {

	private static List<User> users;
	private static Map<Long, User> loginUsers = new HashMap<Long, User>();

	static {
		users = new ArrayList<User>();
		// users.add(new User("riva", "123"));
		users.add(new Admin("adminko", "123"));
		String[][] db = new String[][] { { "azda", "10.98.48.249" }, { "izak", "10.98.48.250" }, { "dsav", "10.98.48.240" }, { "atab", "10.98.48.244" },
				{ "oshu", "10.98.48.251" }, { "akru", "10.98.48.247" }, { "syar", "10.98.48.245" }, { "spet", "10.98.48.248" }, { "riva", "10.98.48.239" },
				{ "misk", "10.98.48.246" }, { "mpar", "10.98.48.251" }, { "apop", "10.98.48.232" }, { "rdek", "10.98.48.222" }, { "evgb", "10.98.48.252" },
				{ "dgre", "10.98.48.218" }, { "vlis", "10.98.48.216" }, { "bpor", "10.98.48.251" }, { "aleo", "10.98.48.243" }, { "opil", "10.98.48.217" },
				{ "obil", "10.98.48.238" }, { "ykuz", "10.98.48.224" }, { "msok", "10.98.48.213" }, {"ngal", "10.98.48.207"} };
		for (String[] u : db) {
			users.add(new User(u[0], u[1]));
		}
	}

	public static Long login(String name, String pass) throws UnAutorizationException {
		Long generated = null;
		for (User u : users) {
			if (u.getLogin().equals(name) && u.checkPass(pass)) {
				do {
					generated = generate();
				} while (loginUsers.containsKey(generated));
				loginUsers.put(generated, u);
				return generated;
			}
		}
		throw new UnAutorizationException("User not found");
	}

	private static Long generate() {
		return Math.round(Long.MAX_VALUE * Math.random());
	}

	public static void logout(Long id) {
		loginUsers.remove(id);
	}

	public static String isLogined(Long id) throws UnAutorizationException {
		User u = loginUsers.get(id);
		if (u == null)
			throw new UnAutorizationException("User not autorised");
		else
			return u.getLogin();
	}

	public static void checkAdmin(long id) throws UnAutorizationException {
		isLogined(id);
		User u = loginUsers.get(id);
		u.checkPrivilegions(Privilege.ADMIN);
	}

}
